package sisi.enquires;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.WrongValuesException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.DropEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Groupbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Timebox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;
import org.zkoss.zul.event.PagingEvent;

import sisi.General;
import sisi.agents.Agent;
import sisi.agents.AgentController;
import sisi.agents.Portsagent;
import sisi.agents.PortsagentsController;
import sisi.corporation.Corporation;
import sisi.corporation.CorporationController;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.products.Product;
import sisi.products.ProductsController;
import sisi.suppliers.Supplier;
import sisi.unitmeasure.UnitmeasureController;
import sisi.yacht.Anayacht;
import sisi.yacht.AnayachtController;


/**
 * ReqshipfuelassWindow.java - Controller class for <i>reqshipfuelass window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 10/1/2014
 * 
 */


@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class ReqshipfuelassWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window windowReqshipfuelass, windowEditReqshipfuelass, windowEditReqshipfuelassDetail;
private Textbox tbCerca;
private Listbox boxReqshipfuelass, boxDetail;
private List<Reqshipfuelass> lista_Reqshipfuelass;
private boolean lNuovo;
private Toolbarbutton buttonSeleziona;
private ListModelList listModelList, listModelListDetail;
private Integer idSelezionato = 0;

protected Map<String, Object> args;
private Object ReqshipfuelassItem;
private Reqshipfuelass modReqshipfuelass;
// edit
private Textbox location;
private Textbox note;
private Textbox status;
private Intbox id;
private Textbox agent;
private Intbox agentid;
private Checkbox art15;
private Checkbox bert;
private Textbox captain;
private Datebox deliverydt;
private Timebox deliverytime;
private Datebox dtup;
private Datebox etadt;
private Timebox etatime;
private Datebox etddt;
private Timebox etdtime;
private Doublebox exchrate;
private Checkbox fuel;
private Textbox fuelconn;
private Intbox idlastport;
private Intbox idnextport;
private Intbox idportref;
private Textbox lastport;
private Textbox locphone;
private Textbox nextport;
private Textbox notea;
private Textbox notes;
private Checkbox oil;
private Checkbox oth;
private Checkbox paidc;
private Checkbox paids;
private Textbox pobox;
private Textbox porttoref;
private Checkbox refused;
private Textbox satcom;
private Checkbox spare;
private Textbox vesselname;
private Listbox boxVesselname;
private Groupbox type;
private Combobox portagents;
//, boxPorttoref, boxLastport, boxNextport;
//private ListModelList lmlPorttoref, lmlLastport, lmlNextport;
private Intbox vesselnameid;
private int quantitaRecords = 0;
private final String PAG_REQSHIPFUELASS = "pageReqshipfuelass";
private Integer cercaVesselnameid;
private String cercaVesselname;
private Label lblSuggestedid;
private Intbox idSuggested;
private Textbox corporation;
private Listheader lhSeq;
// NEW/EDIT DETAIL
private Intbox productid, seq;
private Textbox productname, stat, noteproduct;
private Doublebox quantity;
private Combobox um;
private Reqshipfuelassdetail modReqshipfuelassDetail;
private Button btnAgent, btnReqshipfuelassignement;
private boolean primavolta = true;

		public void onCreate$windowReqshipfuelass(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N": tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		
		quantitaRecords = new ReqshipfuelassController().getCount(null, null);
		
		Paging pag = (Paging) getFellow(PAG_REQSHIPFUELASS);
		pag.setTotalSize(quantitaRecords);

		redraw(0, 20);
		
		pag.addEventListener("onPaging", new EventListener() {

			public void onEvent(Event event) {
				PagingEvent pe = (PagingEvent) event;

				Paging pag = (Paging) getFellow(PAG_REQSHIPFUELASS);
				final int PAGE_SIZE = pag.getPageSize();

				int pgno = pe.getActivePage();
				int ofs = pgno * PAGE_SIZE;
				redraw(ofs, PAGE_SIZE);
			}
		});
		
		/*
		listModelList = new ListModelList();
		lista_Reqshipfuelass = new ReqshipfuelassController().getList(null);
		listModelList.addAll(lista_Reqshipfuelass);
		boxReqshipfuelass.setModel(listModelList);
		boxReqshipfuelass.setItemRenderer(new ReqshipfuelassItemRenderer());
		*/

		/*
		if (idSelezionato != null && idSelezionato != 0) {
			for (int i = 0; i < lista_Reqshipfuelass.size(); i++) {
				Reqshipfuelass record = (Reqshipfuelass) lista_Reqshipfuelass
						.get(i);
				if (record.getId() == idSelezionato.intValue()) {
					boxReqshipfuelass.setSelectedIndex(i);
					break;
				}
			}
		}
		*/

}
		
	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);
	}
	
	private void redraw(int firstResult, int maxResults) {

		Listbox lst = boxReqshipfuelass;
		lst.getItems().clear();

		int quanti = Math.min(quantitaRecords, maxResults);
		
		List<Reqshipfuelass> lista_Reqshipfuelass = new ReqshipfuelassController().getList(cercaVesselnameid, cercaVesselname, firstResult, quanti);

		listModelList = new ListModelList();
		listModelList.addAll(lista_Reqshipfuelass);
		boxReqshipfuelass.setModel(listModelList);
		boxReqshipfuelass.setItemRenderer(new ReqshipfuelassItemRenderer());

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}

	public void onClick$buttonCerca(Event event) {
		cerca();
	}


	private void cerca(){
		
		this.boxReqshipfuelass.clearSelection();
		quantitaRecords = new ReqshipfuelassController().getCount(null, tbCerca.getValue());
		cercaVesselname = tbCerca.getValue();

		Paging pag = (Paging) getFellow(PAG_REQSHIPFUELASS);
		pag.setTotalSize(quantitaRecords);
		final int PAGE_SIZE = pag.getPageSize();

		redraw(0, PAGE_SIZE);

	}

	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}

	public void onClick$buttonSeleziona(Event event) {

		seleziona();

}

	public void seleziona() {
		if (boxReqshipfuelass.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oReqshipfuelass = boxReqshipfuelass.getSelectedItem().getAttribute("rigaReqshipfuelass");
			String codiceSelezionato = ""+((Reqshipfuelass) oReqshipfuelass).getId();
			Sessions.getCurrent().setAttribute("codiceReqshipfuelassSelezionato", codiceSelezionato);
			windowReqshipfuelass.detach();
		}
	}

	public void onClick$buttonNuovo(Event event) {
		modifica(true);
		cerca(); // per visualizzare l'ultimo inserito come prima nel elenco.
	}

	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}

	private void modifica(boolean nuovo){
		try {

			int nIndex = boxReqshipfuelass.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a row to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxReqshipfuelass", boxReqshipfuelass);
				Window finestraEditReqshipfuelass = (Window) Executions.createComponents("/editReqshipfuelass.zul", null, map);
				finestraEditReqshipfuelass.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}

	public void onClick$buttonCancella(Event event) {
	// TODO Auto-generated method stub

	}

	public class ReqshipfuelassItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Reqshipfuelass) data).getId()).setParent(li);
			new Listcell(""+((Reqshipfuelass) data).getVesselname()).setParent(li);
			li.setAttribute("rigaReqshipfuelass", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}


// EDIT: NEW/MODIFY
	public void onCreate$windowEditReqshipfuelass(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		boxReqshipfuelass = (Listbox) args.get("boxReqshipfuelass");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}
		
		if (lNuovo){
			primavolta = true;
			btnReqshipfuelassignement.setDisabled(true);
		} else {
			primavolta = false;
			btnReqshipfuelassignement.setDisabled(false);
		}
		
		// carico lista yachts
		List<Anayacht> yachts = new AnayachtController().getAnayachtList(null);
        ListModelList lm = new ListModelList();
		lm.addAll(yachts);
		boxVesselname.setModel(lm);
		boxVesselname.setItemRenderer(new RendererYachts());
		boxVesselname.setSelectedIndex(-1);
		
		if (!lNuovo) {
			windowEditReqshipfuelass.setTitle("Edit Ship's Enquiry");
			ReqshipfuelassItem = boxReqshipfuelass.getSelectedItem().getAttribute("rigaReqshipfuelass");
			modReqshipfuelass = new ReqshipfuelassController().refresh((Reqshipfuelass) ReqshipfuelassItem);
			ReqshipfuelassItem = modReqshipfuelass;
			location.setValue(modReqshipfuelass.getLocation());
			note.setValue(modReqshipfuelass.getNote());
			status.setValue(modReqshipfuelass.getStatus());
			id.setValue(modReqshipfuelass.getId());
			id.setReadonly(true);
			agent.setValue(modReqshipfuelass.getAgent());
			agentid.setValue(modReqshipfuelass.getAgentid());
			
			if ( modReqshipfuelass.getAgentid()!=null && modReqshipfuelass.getAgentid().compareTo(0) != 0 ){
				Agent tmpAgent = new AgentController().getxId(modReqshipfuelass.getAgentid());
				modReqshipfuelass.setAgent(tmpAgent.getCompanyname());
				agent.setValue(tmpAgent.getCompanyname());
			}
			
			
			art15.setChecked(modReqshipfuelass.getArt15());
			bert.setChecked(modReqshipfuelass.getBert());
			captain.setValue(modReqshipfuelass.getCaptain());
			if (modReqshipfuelass.getDeliverydt()!=null){
				deliverydt.setValue( (java.util.Date) (modReqshipfuelass.getDeliverydt()));
			}
			if (modReqshipfuelass.getDeliverytime()!=null){
				deliverytime.setValue( (java.util.Date) (modReqshipfuelass.getDeliverytime()));
			}
			if (modReqshipfuelass.getDtup()!=null){
				dtup.setValue( (java.util.Date) (modReqshipfuelass.getDtup()));
			}
			if (modReqshipfuelass.getEtadt()!=null){
				etadt.setValue( (java.util.Date) (modReqshipfuelass.getEtadt()));
			}
			if (modReqshipfuelass.getEtatime()!=null){
				etatime.setValue( (java.util.Date) (modReqshipfuelass.getEtatime()));
			}
			if (modReqshipfuelass.getEtddt()!=null){
				etddt.setValue( (java.util.Date) (modReqshipfuelass.getEtddt()));
			}
			if (modReqshipfuelass.getEtdtime()!=null){
				etdtime.setValue( (java.util.Date) (modReqshipfuelass.getEtdtime()));
			}
			exchrate.setValue(modReqshipfuelass.getExchrate());
			fuel.setChecked(modReqshipfuelass.getFuel());
			fuelconn.setValue(modReqshipfuelass.getFuelconn());
			idlastport.setValue(modReqshipfuelass.getIdlastport());
			idnextport.setValue(modReqshipfuelass.getIdnextport());
			idportref.setValue(modReqshipfuelass.getIdportref());
			lastport.setValue(modReqshipfuelass.getLastport());
			locphone.setValue(modReqshipfuelass.getLocphone());
			nextport.setValue(modReqshipfuelass.getNextport());
			notea.setValue(modReqshipfuelass.getNotea());
			notes.setValue(modReqshipfuelass.getNotes());
			oil.setChecked(modReqshipfuelass.getOil());
			oth.setChecked(modReqshipfuelass.getOth());
			paidc.setChecked(modReqshipfuelass.getPaidc());
			paids.setChecked(modReqshipfuelass.getPaids());
			pobox.setValue(modReqshipfuelass.getPobox());
			porttoref.setValue(modReqshipfuelass.getPorttoref());
			refused.setChecked(modReqshipfuelass.getRefused());
			satcom.setValue(modReqshipfuelass.getSatcom());
			spare.setChecked(modReqshipfuelass.getSpare());
			vesselname.setValue(modReqshipfuelass.getVesselname());
			vesselnameid.setValue(modReqshipfuelass.getVesselnameid());
			lblSuggestedid.setVisible(false);
			idSuggested.setVisible(false); 
			
			// aggiorno visualizzazione dati esistenti dello yacht
			if (modReqshipfuelass.getVesselnameid()!=null && Integer.valueOf( modReqshipfuelass.getVesselnameid())!=null && Integer.valueOf( modReqshipfuelass.getVesselnameid() ) > 0 ){
				Anayacht yacht = new AnayachtController().getAnayachtxId(Integer.valueOf( modReqshipfuelass.getVesselnameid() ));
				if (yacht!=null){ 
					for (int i = 0; i < lm.getSize(); i++) {
						Anayacht yacht2 = (Anayacht)lm.get(i);
						if (yacht2.getId().equals(yacht.getId())){
							boxVesselname.setSelectedIndex(i);
							aggDatiYacht();
							break;
						}
					}
				}
			}

			
			// aggiorno visualizzazione dati esistenti detail
			List<Reqshipfuelassdetail> detail = new ReqshipfuelassdetailController().getList(modReqshipfuelass.getId());
			int i = 0;
			for (Reqshipfuelassdetail reqshipfuelassdetail : detail) {
				//reqshipfuelassdetail.setSeq( (i+++1)*10); modificato il 24/3/2014, perchè nella procedura request for a quote sono abbituati a vedere le sequenze da uno in uno.
				reqshipfuelassdetail.setSeq( (i+++1) );
			}
			
			listModelListDetail = new ListModelList();
			listModelListDetail.addAll(detail);
			boxDetail.setModel(listModelListDetail);
			boxDetail.setItemRenderer(new RendererDetail());
			lhSeq.sort(true, true);
			
			
			// riempo combobox ports agent
			if (idportref.getValue()!=0){
				List<Portsagent> listPortagents = new PortsagentsController().getListxIdPort(idportref.getValue());
				ListModelList lmlPortAgents = new ListModelList(listPortagents);
				portagents.setModel(lmlPortAgents);
				portagents.setItemRenderer(new PortAgentsItemRenderer());
				
				// TODO puntatore su agente selezionato.
				if (agent.getValue()!=null && !agent.getValue().isEmpty()){
					portagents.setValue(agentid.getValue() + " - " + agent.getValue());
				}
				
			}

			
			
		} else {
			windowEditReqshipfuelass.setTitle("New Ship's Enquiry");
			// suggested number
			int valore = new ReqshipfuelassController().lastIdPlusOne();
			idSuggested.setValue( valore );
			dtup.setValue( new java.util.Date() );

			listModelListDetail = new ListModelList();
			boxDetail.setModel(listModelListDetail);
			boxDetail.setItemRenderer(new RendererDetail());
			
			
			windowEditReqshipfuelass.addEventListener("onClose", new EventListener() {

				public void onEvent(Event event) {
					if (!controlloChiusura()){
						event.stopPropagation();
					}
				}
			});
			
			
		}
		
		
		id.setFocus(true);

	}

	
	/*
	public void onClose$windowEditReqshipfuelass(Event event){
		event.stopPropagation();
		if (controlloChiusura()){
			windowEditReqshipfuelass.detach();
		}
	}
	*/
	
	public void onClick$btnAnnulla(Event event){
		if (controlloChiusura()){
			windowEditReqshipfuelass.detach();
		}
	}

	private boolean controlloChiusura(){
		boolean ok = true;
		if (lNuovo){
			if (Messagebox.show("Exit without save?",
					"Information", Messagebox.YES | Messagebox.NO,
					Messagebox.QUESTION) == Messagebox.YES) {
				ok = true;
				// esco senza salvare ed è un nuovo movimento, quindi cancello eventuale assignement creato
				if (id.getValue()!=null){
					Reqshipfuelassignement assignement = new ReqshipfuelassignementController().getxIdRef(id.getValue());
					if (assignement!=null){
						new ReqshipfuelassignementController().remove(assignement);
					}
				}
				
			} else {
				ok = false;
			}
		}
		return ok;
	}
	
	private void validateFormEdit(){
		
		ArrayList<WrongValueException> wvea = new ArrayList<WrongValueException>();

		String mess = "This field may not be empty";

		
		if (id.getValue()==null ){
			wvea.add( new WrongValueException(id, mess) );
		}
		
		if (lNuovo && id.getValue()!=null){
			// controllo che l'id non esista già
			Reqshipfuelass tmpReqshipfuelass = new ReqshipfuelassController().getxId(id.getValue());
			if (tmpReqshipfuelass != null && tmpReqshipfuelass.getId() != null){
				wvea.add( new WrongValueException(id, "Reference # exist in database!") );
			}
		}

		
		if (vesselnameid.getValue()==null ){
			wvea.add( new WrongValueException(vesselnameid, mess) );
		}
		
		if (etadt.getValue()==null ){
			//wvea.add( new WrongValueException(etadt, mess) );
		}

		if (etatime.getValue()==null ){
			//wvea.add( new WrongValueException(etatime, mess) );
		}
		if (etddt.getValue()==null ){
			//wvea.add( new WrongValueException(etddt, mess) );
		}

		if (etdtime.getValue()==null ){
			//wvea.add( new WrongValueException(etdtime, mess) );
		}
		if (deliverydt.getValue()==null ){
			wvea.add( new WrongValueException(deliverydt, mess) );
		} else {
			if (deliverydt.getValue().compareTo(new java.util.Date())<0 ){
				General.showNotify("Delivery date can't be less than today date!", null, 3000, "warning");
			}
		}
		
		
		
		
		/* a richiesta l'ora non è più obbligatoria
			if (deliverytime.getValue()==null ){
				wvea.add( new WrongValueException(deliverytime, mess) );
			}
		*/

		
		if (dtup.getValue()==null ){
			wvea.add( new WrongValueException(dtup, mess) );
		}

		if (porttoref.getValue()==null || porttoref.getValue().isEmpty() ){
			wvea.add( new WrongValueException(porttoref, mess) );
		}
		if (!fuel.isChecked() && !oil.isChecked() && !bert.isChecked() && !spare.isChecked() && !oth.isChecked()){
			wvea.add( new WrongValueException(type, "Field TYPE is compulsory") );
		}
		

		if (wvea.size()>0){

			WrongValueException [] wve = new WrongValueException[wvea.size()];
			for (int i = 0; i < wvea.size(); i++) {
				wve[i] = wvea.get(i);
			}
			throw new WrongValuesException(wve);
		}
	}

	
	public void onClick$btnAgent(Event event){
		selectAgent(event);
	}
	
	private void selectAgent(Event event){
		Sessions.getCurrent().setAttribute("codiceAgentSelezionato",
				"");
			HashMap map = new HashMap();
			map.put("tastoSeleziona", "S");
			map.put("idselezionato", agentid.getValue() );
			
			Window finestraBrowseAgent = (Window) Executions.createComponents(
					"/agent.zul", null, map);
			finestraBrowseAgent.doModal();
			
			String codiceSelezionato = (String) Sessions.getCurrent()
					.getAttribute("codiceAgentSelezionato");
			if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
				//agente.setValue(codiceSelezionato);
				Agent agente = new AgentController().getxId(Integer.valueOf(codiceSelezionato));
				agent.setValue(agente.getCompanyname());
				agentid.setValue(agente.getAgentid());
			}
	}
	
	public void onChange$deliverydt(){
		//System.out.println(deliverydt.getValue().compareTo(new java.util.Date()));
		if (deliverydt.getValue().compareTo(new java.util.Date())<0 ){
			General.showNotify("Delivery date can't be less than today date!", null, 3000, "warning");
		}
	}
	
	public void onBlur$id(Event event){
		//controlloReference();
	}

	
	public void onOK$id(Event event){
		//controlloReference();
	}
	
	public void onChange$id(Event event){
		controlloReference();
	}
	
	public void onSelect$portagents(){
		String codiceSelezionato = portagents.getValue();
		if (codiceSelezionato!=null && !codiceSelezionato.isEmpty() ){
			codiceSelezionato = codiceSelezionato.substring(0, codiceSelezionato.indexOf("-")-1);
			Agent agente = new AgentController().getxId(Integer.valueOf(codiceSelezionato));
			if (agente==null || agente.getAgentid()==null ){
				new General().errorBox("Agent "+portagents.getValue()+" does not exist in the table Agents!!", "ERROR");
			} else {
				agent.setValue(agente.getCompanyname());
				agentid.setValue(agente.getAgentid());
			}
		}
	}
	
	private void controlloReference(){
		if (lNuovo &&  !id.getValue().equals(idSuggested.getValue()) ){
			String mess = "Warning!! You are assigning a reference not equal to suggested reference. Do you want to do this?";
			if ( Messagebox.show(mess, "Reference #",
					Messagebox.YES | Messagebox.NO, Messagebox.QUESTION) != Messagebox.YES) {
				id.setValue(idSuggested.getValue());
				id.setFocus(true);
			} else {
				
			}
		}
	}
	
	public void onClick$btnConferma(Event event){
		
		
		validateFormEdit();
		
		if (lNuovo){
			// controllo che l'id non esista già
			Reqshipfuelass tmpReqshipfuelass = new ReqshipfuelassController().getxId(id.getValue());
			if (tmpReqshipfuelass != null && tmpReqshipfuelass.getId() != null){
				new General().errorBox("Reference # exist in database!", "Reference #");
				return;
			}
			
			
			modReqshipfuelass = new Reqshipfuelass();
			modReqshipfuelass.setStatus("SE");
		} else {

		}
		String testoMsg = "";

		modReqshipfuelass.setLocation(location.getValue());
		modReqshipfuelass.setNote(note.getValue());
		modReqshipfuelass.setStatus(status.getValue());
		modReqshipfuelass.setId(id.getValue());
		
		if (modReqshipfuelass.getStatus()==null || modReqshipfuelass.getStatus().isEmpty() ){
			modReqshipfuelass.setStatus("SE");
		}
		
		String codiceSelezionato = portagents.getValue();
		if (codiceSelezionato!=null && !codiceSelezionato.isEmpty() ){
			codiceSelezionato = codiceSelezionato.substring(0, codiceSelezionato.indexOf("-")-1);
			Agent agente = new AgentController().getxId(Integer.valueOf(codiceSelezionato));
			if (agente.getAgentid()!=null){
				agent.setValue(agente.getCompanyname());
				agentid.setValue(agente.getAgentid());
			}
		}
		
		if (portagents.getSelectedIndex()>0){
			modReqshipfuelass.setAgent(agent.getValue());
			modReqshipfuelass.setAgentid(agentid.getValue());		
		} else {
			modReqshipfuelass.setAgent("");
			modReqshipfuelass.setAgentid(0);			
		}
		
		modReqshipfuelass.setArt15(art15.isChecked());
		modReqshipfuelass.setBert(bert.isChecked());
		modReqshipfuelass.setCaptain(captain.getValue());
		modReqshipfuelass.setDeliverydt( (deliverydt.getValue() != null ? General.date2SqlTimestamp(deliverydt.getValue()): null) );
		modReqshipfuelass.setDeliverytime( (deliverytime.getValue() != null ? new Timestamp( deliverytime.getValue().getTime() ): null) );
		modReqshipfuelass.setDtup( (dtup.getValue() != null ? General.date2SqlTimestamp(dtup.getValue()): null) );
		modReqshipfuelass.setEtadt( (etadt.getValue() != null ? General.date2SqlTimestamp(etadt.getValue()): null) );
		modReqshipfuelass.setEtatime( (etatime.getValue() != null ? new Timestamp( etatime.getValue().getTime() ) : null) );
		modReqshipfuelass.setEtddt( (etddt.getValue() != null ? General.date2SqlTimestamp(etddt.getValue()): null) );
		modReqshipfuelass.setEtdtime( (etdtime.getValue() != null ? new Timestamp( etdtime.getValue().getTime() ): null) );
		modReqshipfuelass.setExchrate(exchrate.getValue());
		modReqshipfuelass.setFuel(fuel.isChecked());
		modReqshipfuelass.setFuelconn(fuelconn.getValue());
		modReqshipfuelass.setIdlastport(idlastport.getValue());
		modReqshipfuelass.setIdnextport(idnextport.getValue());
		modReqshipfuelass.setIdportref(idportref.getValue());
		modReqshipfuelass.setLastport(lastport.getValue());
		//modReqshipfuelass.setLocphone(locphone.getValue());
		modReqshipfuelass.setNextport(nextport.getValue());
		modReqshipfuelass.setNotea(notea.getValue());
		modReqshipfuelass.setNotes(notes.getValue());
		modReqshipfuelass.setOil(oil.isChecked());
		modReqshipfuelass.setOth(oth.isChecked());
		modReqshipfuelass.setPaidc(paidc.isChecked());
		modReqshipfuelass.setPaids(paids.isChecked());
		//modReqshipfuelass.setPobox(pobox.getValue());
		modReqshipfuelass.setPorttoref(porttoref.getValue());
		modReqshipfuelass.setRefused(refused.isChecked());
		//modReqshipfuelass.setSatcom(satcom.getValue());
		modReqshipfuelass.setSpare(spare.isChecked());
		modReqshipfuelass.setVesselname(vesselname.getValue());
		modReqshipfuelass.setVesselnameid(vesselnameid.getValue()); 

		if (lNuovo){
			modReqshipfuelass = new ReqshipfuelassController().add(modReqshipfuelass);
			testoMsg = "New Reqshipfuelass: "+ General.trimNull( modReqshipfuelass.getVesselname() );
		} else {
			new ReqshipfuelassController().update(modReqshipfuelass);
			testoMsg = "Updating Reqshipfuelass: "+ General.trimNull( modReqshipfuelass.getVesselname() );
		}
		
		
		// cancello detail esistente e inserisco nuove righe
		if ( !lNuovo ) {
			List<Reqshipfuelassdetail> dettOld = new ReqshipfuelassdetailController().getList(modReqshipfuelass.getId());
			for (Reqshipfuelassdetail reqshipfuelassdetail : dettOld) {
				new ReqshipfuelassdetailController().remove(reqshipfuelassdetail);
			}
		}
		// inserisco nuovi records del detail
		for (int i = 0; i < boxDetail.getItemCount(); i++) {
			Object oDetail = boxDetail.getItemAtIndex(i).getAttribute(
					"rigaDetail");
			Reqshipfuelassdetail detail = (Reqshipfuelassdetail)oDetail; 
			detail.setId(modReqshipfuelass.getId());
			//detail.setSeq( ( (i+1)*10 ) );
			if (lNuovo){
				detail.setStat("SE");
			} else {
				if (detail.getStat()==null || detail.getStat().isEmpty()){
					detail.setStat("SE");
				}
			}
			detail.setRefused(false);
			new ReqshipfuelassdetailController().add(detail);
		}
		

		General.showNotify( testoMsg, windowEditReqshipfuelass);

		// aggiorna listbox

		if (lNuovo){
			ListModelList lml = (ListModelList) boxReqshipfuelass.getListModel();
			lml.add(modReqshipfuelass);
			boxReqshipfuelass.setSelectedIndex(lml.indexOf(modReqshipfuelass));
			
		} else {
			ListModelList lml = (ListModelList) boxReqshipfuelass.getListModel();
			Object oReqshipfuelassItem = boxReqshipfuelass.getSelectedItem().getAttribute("rigaReqshipfuelass");
			if (lml.indexOf(oReqshipfuelassItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oReqshipfuelassItem), modReqshipfuelass);
			}
		}
		
		
		if ( (lNuovo && !primavolta) || !lNuovo ){
			windowEditReqshipfuelass.detach();
		} else {
			btnReqshipfuelassignement.setDisabled(false);
			primavolta = false;
			lNuovo = false;
		}
		
	}

	
	public void onSelect$boxVesselname(){
		int rowSelected = boxVesselname.getSelectedIndex();
		if (rowSelected>=0){
			Object oYacht = boxVesselname.getSelectedItem().getAttribute("rigaAnayacht");
			Anayacht yacht = (Anayacht)oYacht;
			vesselname.setValue(yacht.getName());
			vesselnameid.setValue(yacht.getId());
		}
		aggDatiYacht();
	}
	
	private void aggDatiYacht(){
		if (vesselnameid.getValue()==null){
			corporation.setValue("");
			captain.setValue("");
			locphone.setValue("");
			satcom.setValue("");
			fuelconn.setValue("");
		} else {
			Anayacht yacht = new AnayachtController().getAnayachtxId( vesselnameid.getValue() );
			corporation.setValue(yacht.getCorporation());
			captain.setValue(yacht.getCaptain());
			locphone.setValue(""); // TODO capire con Flavio che dato mettere
			satcom.setValue(yacht.getSatcomtel());
			fuelconn.setValue(yacht.getFuelconn());
		}
	}

	
	public void onClick$btnPorttoref(Event event){
		Sessions.getCurrent().setAttribute("codicePortSelezionato",
				"");
			HashMap map = new HashMap();
			map.put("tastoSeleziona", "S");
			map.put("idselezionato", idportref.getValue());
			Window winPort = (Window) Executions.createComponents(
					"/port.zul", null, map);
			winPort.doModal();
			String codiceSelezionato = (String) Sessions.getCurrent()
					.getAttribute("codicePortSelezionato");
			if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
				Port port = new PortController().getPortxId(Integer.valueOf(codiceSelezionato));
				porttoref.setValue(port.getPortname());
				idportref.setValue(port.getId());
				note.setValue(port.getNote()); 
				
				// riempo combobox ports agent
				List<Portsagent> listPortagents = new PortsagentsController().getListxIdPort(idportref.getValue());
				ListModelList lmlPortAgents = new ListModelList(listPortagents);
				portagents.setModel(lmlPortAgents);
				portagents.setItemRenderer(new PortAgentsItemRenderer());
				
			}
	}
	
	
	private class PortAgentsItemRenderer implements ComboitemRenderer {
		
		@Override
		public void render(Comboitem item, Object data, int index)
				throws Exception {
			
			Portsagent portagent = (Portsagent)data;
			
			if (portagent.getAgentid()==null){
				item.setLabel("");
				item.setDescription("");
			} else {
				
				String agenteCompanyName = portagent.getAgentname();
				if ( portagent.getAgentid()!=null && portagent.getAgentid().compareTo(0) != 0 ){
					Agent tmpAgent = new AgentController().getxId(portagent.getAgentid());
					if (tmpAgent!=null && tmpAgent.getAgentid()!=null && tmpAgent.getAgentid().compareTo(0) != 0 ){
						agenteCompanyName  = tmpAgent.getCompanyname();
					}
				}
				
				item.setLabel(""+portagent.getAgentid() + " - " + agenteCompanyName );
				//item.setDescription("P: "+( portagent.getPhysical()==null || !portagent.getPhysical() ? "NO" : "SI" ) + " T: "+( portagent.getTrader()==null || !portagent.getTrader() ? "NO" : "SI") );
			}
		}


	}
	
	
	public void onClick$btnLastport(Event event){
		Sessions.getCurrent().setAttribute("codicePortSelezionato",
				"");
			HashMap map = new HashMap();
			map.put("tastoSeleziona", "S");
			map.put("idselezionato", idlastport.getValue());
			Window winPort = (Window) Executions.createComponents(
					"/port.zul", null, map);
			winPort.doModal();
			String codiceSelezionato = (String) Sessions.getCurrent()
					.getAttribute("codicePortSelezionato");
			if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
				Port port = new PortController().getPortxId(Integer.valueOf(codiceSelezionato));
				lastport.setValue(port.getPortname());
				idlastport.setValue(port.getId());
			}
	}

	public void onClick$btnNextport(Event event){
		Sessions.getCurrent().setAttribute("codicePortSelezionato",
				"");
			HashMap map = new HashMap();
			map.put("tastoSeleziona", "S");
			map.put("idselezionato", idnextport.getValue());
			Window winPort = (Window) Executions.createComponents(
					"/port.zul", null, map);
			winPort.doModal();
			String codiceSelezionato = (String) Sessions.getCurrent()
					.getAttribute("codicePortSelezionato");
			if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
				Port port = new PortController().getPortxId(Integer.valueOf(codiceSelezionato));
				nextport.setValue(port.getPortname());
				idnextport.setValue(port.getId());
			}
	}

	public void onClick$btnReqshipfuelassignement(Event event){
			HashMap map = new HashMap();
			map.put("tastoSeleziona", "N");
			map.put("idselezionato", id.getValue());

			map.put("par_idport", idportref.getValue() );
			map.put("par_idnextport", idnextport.getValue() );
			map.put("par_idlastport", idlastport.getValue() );			
			map.put("par_idyacht", vesselnameid.getValue() );
			map.put("par_etadt", etadt.getValue() );
			map.put("par_etatm", etatime.getValue() );
			map.put("par_etddt", etddt.getValue() );
			map.put("par_etdtm", etdtime.getValue() );
			map.put("par_agentid", agentid.getValue() );
			map.put("par_location", location.getValue() );
			map.put("par_deliverydt", deliverydt.getValue());
			map.put("par_deliverytm", deliverytime.getValue());
			Window winPort = (Window) Executions.createComponents(
					"/reqshipfuelassignement.zul", null, map); 
			winPort.doModal();
	}
	
	// NEW/EDIT DETAIL

	
	public void onCreate$windowEditReqshipfuelassDetail(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		//idSelezionato = (Integer) args.get("idselezionato");
		boxDetail = (Listbox) args.get("boxDetail");
		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		
		List<String> listUM = new UnitmeasureController().getUMList1Campo();
		ListModelList lm = new ListModelList(listUM);
	
		if (!lNuovo){

			Object oDetail = boxDetail.getSelectedItem().getAttribute("rigaDetail");
			modReqshipfuelassDetail = (Reqshipfuelassdetail) oDetail;
			productid.setValue(modReqshipfuelassDetail.getProductid());
			productname.setValue(modReqshipfuelassDetail.getProductname());
			quantity.setValue(modReqshipfuelassDetail.getQuantity());
			um.setValue(modReqshipfuelassDetail.getUm());
			stat.setValue(modReqshipfuelassDetail.getStat());
			noteproduct.setValue(modReqshipfuelassDetail.getNote());
			seq.setValue(modReqshipfuelassDetail.getSeq());
			
			if (!modReqshipfuelassDetail.getUm().isEmpty()){
				um.setValue(modReqshipfuelassDetail.getUm());
				lm.addToSelection(modReqshipfuelassDetail.getUm());

			}
		} else {
			seq.setValue( (boxDetail.getItemCount()+1));			
		}
		
		um.setModel(lm);
	
	}
	
	public void onClick$buttonNuovoDetail(Event event){
		modificaDetail(true);
	}
	

	public void onClick$buttonModificaDetail(Event event){
		modificaDetail(false);
	}

	
	public void onDoubleClickedDetail(Event event) {
			modificaDetail(false);
	}
	
	
	private void modificaDetail(boolean nuovo){
		try {

			int nIndex = boxDetail.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata
				Messagebox.show("Select a row to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);
			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxDetail", boxDetail);
				Window finestraEditReqshipfuelassDetail = (Window) Executions.createComponents("/editReqshipfuelassDetail.zul", null, map);
				finestraEditReqshipfuelassDetail.doModal();
			}
		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	public void onClick$buttonCancellaDetail(Event event){
		int nIndex = boxDetail.getSelectedIndex();

		if (nIndex == -1) { // nessuna riga selezionata
			Messagebox.show("Select a row to Delete",
					"Information", Messagebox.OK, Messagebox.INFORMATION);
			return;
		} else {	
			ListModelList lml = (ListModelList) boxDetail.getListModel();
			lml.remove(nIndex);
			boxDetail.setSelectedIndex(nIndex - 1);
			lhSeq.sort(true, true);
		}
	}
	
	
	private void validateFormEditDetail(){
		
		ArrayList<WrongValueException> wvea = new ArrayList<WrongValueException>();

		
		if (productname.getValue()==null || productname.getValue().isEmpty()){
			wvea.add( new WrongValueException(productname, "The field Product Name may not be empty") );
		}

		if (um.getValue()==null || um.getValue().isEmpty()){
			wvea.add( new WrongValueException(um, "The field Unit Measure may not be empty") );
		}

		if (wvea.size()>0){

			WrongValueException [] wve = new WrongValueException[wvea.size()];
			for (int i = 0; i < wvea.size(); i++) {
				wve[i] = wvea.get(i);
			}
			throw new WrongValuesException(wve);
		}
	}
	
	
	public void onClick$btnConfermaEditDetail(Event event){
		
		
		validateFormEditDetail();
		
		// TODO controllo che  UM sia valida o esistente del elenco UM
		
		
		if (lNuovo){
			modReqshipfuelassDetail = new Reqshipfuelassdetail();
		} else {

		}

		modReqshipfuelassDetail.setProductid(productid.getValue());
		modReqshipfuelassDetail.setProductname(productname.getValue());
		modReqshipfuelassDetail.setNote(noteproduct.getValue());
		modReqshipfuelassDetail.setQuantity(quantity.getValue());
		modReqshipfuelassDetail.setUm(um.getValue());
		modReqshipfuelassDetail.setSeq(seq.getValue());

		windowEditReqshipfuelassDetail.detach();
		// aggiorna listbox

		if (lNuovo){
			ListModelList lml = (ListModelList) boxDetail.getListModel();
			lml.add(modReqshipfuelassDetail);
			boxDetail.setSelectedIndex(lml.indexOf(modReqshipfuelassDetail));
		} else {
			ListModelList lml = (ListModelList) boxDetail.getListModel();
			Object oReqshipfuelassDetailItem = boxDetail.getSelectedItem().getAttribute("rigaDetail");
			if (lml.indexOf(oReqshipfuelassDetailItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oReqshipfuelassDetailItem), modReqshipfuelassDetail);
				//lhSeq.sort(true, true);
			}
		}

	}
	
	public void onClick$btnAnnullaEditDetail(Event event){
		windowEditReqshipfuelassDetail.detach();		
	}
	
	public void onDropMove(Event event) throws Exception {
		
		ForwardEvent fwe = (ForwardEvent) event;

		DropEvent dropEvent = (DropEvent) fwe.getOrigin();	
		Listitem draggedItem = (Listitem) dropEvent.getDragged();
		Listitem droppedItem = (Listitem) dropEvent.getTarget();

		move(draggedItem, droppedItem);
	}
	
	void move(Listitem dragged, Listitem droppedItem) {
		if (dragged instanceof Listitem) {
			//if (dragged.getParent().getId().equals("boxDetail")) {
			Object oDragged = dragged.getAttribute("rigaDetail");
			Object oDropped = droppedItem.getAttribute("rigaDetail");
			Integer seq1 = ((Reqshipfuelassdetail)oDragged).getSeq();
			Integer seq2 = ((Reqshipfuelassdetail)oDropped).getSeq();
			((Reqshipfuelassdetail)oDragged).setSeq(seq2);
			((Reqshipfuelassdetail)oDropped).setSeq(seq2+1);
			int index = droppedItem.getIndex();
			
			dragged.getParent().insertBefore(dragged, droppedItem);
			
		}

	}
	
	@SuppressWarnings("unused")
	private void rinnumeroSeqDetail(){
		
		List<Listitem> items = boxDetail.getItems();

		ListModel<Reqshipfuelassdetail> model = boxDetail.getListModel();
		
		/*
		for (int i = 0; i < model.getSize(); i++) {
			Reqshipfuelassdetail detail = model.getElementAt(i);
			detail.setSeq((i+1)*10);
		}
		*/
		
		
		ListModelList lml = (ListModelList) boxDetail.getListModel();
		
		/*
		int i = 1;
		for (Object object : lml) {
			Reqshipfuelassdetail detail = (Reqshipfuelassdetail) object;
			detail.setSeq(i++);
		}
		*/
		
		/*
		for (int i = 0; i < boxDetail.getItemCount(); i++) {
			Object oDetail = boxDetail.getItemAtIndex(i).getAttribute(
					"rigaDetail");
			if (oDetail!=null){
				Reqshipfuelassdetail detail = (Reqshipfuelassdetail)oDetail;
				detail.setSeq( (i+1) );
				//lml.set(lml.indexOf(oDetail), detail);
			}
		}
		*/
	}
	
	public void onClick$btnProduct(Event event){
		Sessions.getCurrent().setAttribute("codiceProductSelezionato", "");
		HashMap map = new HashMap();
		map.put("tastoSeleziona", "S");
		map.put("idselezionato", productid.getValue());
		Window winProduct = (Window) Executions.createComponents(
				"/products.zul", null, map);
		winProduct.doModal();
		String codiceSelezionato = (String) Sessions.getCurrent()
				.getAttribute("codiceProductSelezionato");
		if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
			Product product = new ProductsController().getProductxId((Integer.valueOf(codiceSelezionato)));
			productname.setValue(product.getProductname());
			productid.setValue(product.getId());
		}
	}
	
	
	// RENDERERS
	public class RendererYachts implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Anayacht yacht = ((Anayacht) data);
			
			new Listcell(yacht.getName() + " - Id: "+yacht.getId()).setParent(li);
			li.setAttribute("rigaAnayacht", data);
		}
	}
	
	
	
	public class RendererDetail implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Reqshipfuelassdetail detail = ((Reqshipfuelassdetail) data);
			
			new Listcell(""+detail.getId()).setParent(li);
			new Listcell(""+detail.getSeq()).setParent(li);
			new Listcell(""+detail.getProductid()).setParent(li);
			
			Listcell cellProductname = new Listcell(detail.getProductname());
			cellProductname.setStyle("white-space:nowrap;overflow:hidden");
			cellProductname.setParent(li);
			new Listcell(""+detail.getQuantity()).setParent(li);
			new Listcell(detail.getUm()).setParent(li);
			new Listcell(detail.getStat()).setParent(li);
			Listcell cellNote = new Listcell(""+detail.getNote());
			cellNote.setStyle("white-space:nowrap;overflow:hidden");
			cellNote.setParent(li);
			li.setAttribute("rigaDetail", data);
			
			//li.setDraggable("true");
			//li.setDroppable("true");
			//ComponentsCtrl.applyForward(li, "onDrop=onDropMove");

			
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClickedDetail");
		}
	}
	
}
